package xin.yangshuai.juc01.hello;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Question9
 *
 * @author shuai
 * @date 2022/2/20
 */
public class Question9 {

    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();


    public void read() {
        try {
            readWriteLock.readLock().lock();
            System.out.println(Thread.currentThread().getName() + " :: 开始读");

            TimeUnit.MILLISECONDS.sleep(new Random().nextInt(3000));
            System.out.println(Thread.currentThread().getName() + " :: 读完了");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

    public void write() {
        try {
            readWriteLock.writeLock().lock();
            System.out.println(Thread.currentThread().getName() + " :: 开始写");

            TimeUnit.MILLISECONDS.sleep(new Random().nextInt(3000));
            System.out.println(Thread.currentThread().getName() + " :: 写完了");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
}

class Result9 {
    public static void main(String[] args) {

        Question9 question9 = new Question9();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    question9.read();
                }
            }, "read" + i).start();
        }

        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    question9.write();
                }
            }, "write" + i).start();
        }
    }
}

